# backend/app.py
from flask import Flask, request, jsonify, Response
import requests
import os
from dotenv import load_dotenv

load_dotenv()  # 加载环境变量
app = Flask(__name__)

# DeepSeek API配置
DEEPSEEK_API_URL = "http://10.2.8.77:3000"
DEEPSEEK_API_KEY = os.getenv("DEEPSEEK_API_KEY")


@app.route('/api/rate-essay', methods=['POST'])
def rate_essay():
    # 1. 验证请求数据
    data = request.json
    if not data or 'text' not in data:
        return jsonify({"error": "作文内容不能为空"}), 400

    # 2. 调用DeepSeek API
    headers = {
        "Authorization": f"Bearer {DEEPSEEK_API_KEY}",
        "Content-Type": "application/json"
    }

    payload = {
        "model": "deepseek-chat",
        "messages": [
            {
                "role": "system",
                "content": "你是一位专业的语文老师，请根据以下评分标准批改作文：\n1. 立意(30%)\n2. 结构(20%)\n3. 语言(30%)\n4. 创新(20%)"
            },
            {
                "role": "user",
                "content": f"请批改以下作文：\n{data['text']}"
            }
        ],
        "temperature": 0.7,
        "stream": False  # 设为True可启用流式响应
    }

    try:
        # 3. 发送请求到DeepSeek
        response = requests.post(
            DEEPSEEK_API_URL,
            headers=headers,
            json=payload,
            timeout=30
        )
        response.raise_for_status()

        # 4. 返回批改结果
        result = response.json()["choices"][0]["message"]["content"]
        return jsonify({"result": result})

    except Exception as e:
        return jsonify({"error": f"DeepSeek API调用失败: {str(e)}"}), 500


if __name__ == '__main__':
    app.run(port=5000)